package com.yexx.starter.security.pwd;

import com.yexx.starter.security.basic.constant.SecurityConstants;
import com.yexx.starter.security.basic.SecurityUserDetailsService;
import com.yexx.utils.CacheUtil;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * Description: 自定义账户密码 Adapter
 *
 * @author: zuomin (myleszelic@outlook.com)
 * @date: 2020/11/02-15:38
 */
public class PwdAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    private CacheUtil cacheUtil;

    private SecurityUserDetailsService userDetailsService;

    private PasswordEncoder passwordEncoder;

    private Boolean singleSignOn = false;

    public PwdAuthenticationSecurityConfig(CacheUtil cacheUtil, SecurityUserDetailsService userDetailsService, PasswordEncoder passwordEncoder, Boolean singleSignOn) {
        this.cacheUtil = cacheUtil;
        this.userDetailsService = userDetailsService;
        this.passwordEncoder = passwordEncoder;
        this.singleSignOn = singleSignOn;
    }

    @Override
    public void configure(HttpSecurity http) {
        /**
         * 处理 {@link SecurityConstants.PATH#LOGIN_PHONE_NUM_PWD } 请求
         * */
        //自定义SmsCodeAuthenticationFilter过滤器
        PwdAuthenticationFilter pwdAuthenticationFilter = new PwdAuthenticationFilter(SecurityConstants.PATH.LOGIN_PHONE_NUM_PWD, SecurityConstants.PATH.LOGIN_ERROR, singleSignOn);
        pwdAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        pwdAuthenticationFilter.setCacheUtil(cacheUtil);
        pwdAuthenticationFilter.setUserDetailsService(userDetailsService);

        //设置自定义SmsCodeAuthenticationProvider的认证器userDetailsService
        PwdAuthenticationProvider pwdAuthenticationProvider = new PwdAuthenticationProvider();
        pwdAuthenticationProvider.setSecurityUserService(userDetailsService);
        pwdAuthenticationProvider.setPasswordEncoder(passwordEncoder);

        //在UsernamePasswordAuthenticationFilter过滤前执行
        http.authenticationProvider(pwdAuthenticationProvider).addFilterAfter(pwdAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
